package main

import (
	"bufio"
	"fmt"
	"log"
	"net"
	"time"
	"unicode"
)

func main() {
	listener, err := net.Listen("tcp", ":8000")
	if err != nil {
		log.Fatal(err)
	}

	go broadcaster()
	for {
		conn, err := listener.Accept()
		if err != nil {
			log.Print(err)
			continue
		}
		go handleConn(conn)
	}
}

type client chan<- string // an outgoing message channel

var (
	entering = make(chan client)
	leaving  = make(chan client)

	messages = make(chan string) // all incoming client messages
)

func broadcaster() {
	clients := make(map[client]bool) // all connected clients
	for {
		select {
		case msg := <-messages:
			// Broadcast incoming message to all
			// clients' outgoing message channels.
			for cli := range clients {
				select {
				case cli <- msg:
					//
				default:
					//
				}

			}
		case cli := <-entering:
			clients[cli] = true
		case cli := <-leaving:
			delete(clients, cli)
			close(cli)

		}
	}
}

func handleConn(conn net.Conn) {
	ch := make(chan string) // outgoing client messages
	ntimeout := make(chan bool)
	who := conn.RemoteAddr().String()
	fmt.Fprintln(conn, "Please offer your name:")
	var name = ""
	fmt.Fscanf(conn, "%s\n", &name)
	if name != "" {
		c := rune(name[0])
		if unicode.IsLetter(c) || c == '_' {
			who = string(name)
		} else {
			fmt.Fprintf(conn, "Wrong name,will use %s\n", who)
		}
	} else {
		fmt.Fprintf(conn, "not input name,will use %s\n", who)
	}
	go clientWriter(conn, ch)

	ch <- "You are " + who
	messages <- who + ": has arrived"
	entering <- ch

	go func() {
	loop:
		timeout := time.After(5 * time.Minute)
		for {
			select {
			case <-timeout:
				fmt.Println(who, ": timeout...")
				fmt.Fprintln(conn, "长时间未发送消息，自动离线")
				conn.Close()
				return
			case <-ntimeout:
				fmt.Println(who, ": onlining...")
				goto loop
			}
		}
	}()

	input := bufio.NewScanner(conn)
	for input.Scan() {
		messages <- who + ": " + input.Text()
		ntimeout <- true
	}
	fmt.Println(who, ":离线...")
	// NOTE: ignoring potential errors from input.Err()

	leaving <- ch
	messages <- who + " has left"
	conn.Close()
}

func clientWriter(conn net.Conn, ch <-chan string) {
	for msg := range ch {
		fmt.Fprintln(conn, msg) // NOTE: ignoring network errors
	}

}

//8.12
//8.13 √
//8.14 √
//8.15 --
